import type { FilterValue } from 'ant-design-vue/es/table/interface';
import type { Dayjs } from 'dayjs';

import type { SysPostReq } from '#/type/sys_post';

import type { Reactive, Ref } from 'vue';

export default function useFormHook(
  fetchTableData: () => Promise<void> | void,
  formSearch: Reactive<SysPostReq>,
  tablePagination: Reactive<Record<string, any>>,
  tableFilterData: Ref<Record<string, FilterValue>>,
) {
  const formSearchSubmit = () => {
    fetchTableData();
  };
  const formSearchReset = () => {
    // 重置表单数据
    const keys = Object.keys(formSearch) as (keyof SysPostReq)[];
    for (const key of keys) {
      formSearch[key] = undefined as any;
    }
    tablePagination.current = 1;
    tablePagination.pageSize = 10;
    Object.keys(tableFilterData.value).forEach((key) => {
      tableFilterData.value[key] = [];
    });
    fetchTableData();
  };
  const formInputClear = (key: keyof SysPostReq, e: Event) => {
    if ((e.target as HTMLInputElement).value === '') {
      formSearch[key] = undefined as any;
      fetchTableData();
    }
  };
  const formSelectClear = (key: keyof SysPostReq, e: any) => {
    if (e === undefined || (Array.isArray(e) && e.length === 0)) {
      formSearch[key] = undefined as any;
      fetchTableData();
    }
  };

  const formDateRangeClear = (
    key: keyof SysPostReq,
    dates: [Dayjs, Dayjs] | [string, string],
    dateStrings: [string, string],
  ) => {
    if (
      dates === null ||
      dateStrings === null ||
      dateStrings[0] === '' ||
      dateStrings[1] === ''
    ) {
      formSearch[key] = undefined as any;
      fetchTableData();
    }
  };
  return {
    formSearchSubmit,
    formSearchReset,
    formInputClear,
    formSelectClear,
    formDateRangeClear,
  };
}
